<?php
/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * For more information, see <http://www.aljey.com>.
 */

namespace Al\Style\Lib\Form\Element;

use Al\Core\Lib\ConfigurableInterface,
    Al\Core\Lib\Service,
    Al\Style\Lib\Form\Field,
    Al\Doctrine\Lib\Em;

/**
 * A basic html element.
 *
 * @property string $id An element id.
 * @property string $tag An element tag name.
 * @property string $html An element html string.
 * @property array $cls An array of element classes.
 * @property array $attr An array of element attributes.
 * @property string $help A help text to clarify to the user what the purpose of
 *                        this element is (automatically localized).
 * @property bool $required True to make the field required.
 * @property string $name An html form field name.
 * @author Eugene Kuzmenko <mail@aljey.com>
 */
class Element implements ConfigurableInterface {

  /**
   * @var Field
   */
  public $field;

  /**
   * @var array A configuration array.
   */
  public $config = array(
    'html' => '',
    'cls' => array(),
    'attr' => array(),
    'help' => '',
  );

  /**
   * @var array Tags that do not need to be closed.
   */
  private $selfClose = array('area', 'base', 'br', 'col', 'embed', 'hr', 'img',
    'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr');

  /**
   * @param array $params Config array.
   * @param Field $field
   */
  public function __construct($params = array(), Field $field = null) {
    $this->field = $field ? $field : new Field;
    $this->configure(array(
      'id' => uniqid('element-'),
      'required' => true,
      'name' => uniqid('name-'),
    ), $params);
    $this->config['attr']['id'] = $this->id;
    $this->config['attr']['class'] = implode(' ', $this->cls);
    $class = Service::get('em')->entityShortClass($this->field->form->entity);
    $event = Service::get('event');
    $event->on("$class.prePersist", array($this, 'prePersist'));
    $event->on("$class.preUpdate", array($this, 'prePersist'));
  }

  /**
   * Returns a string representation of an element.
   *
   * @return string
   */
  public function __toString() {
    $result = Service::get('template')->render(
      Service::get('config.plugins.Al\Style.form.element'), array(
        'help' => Service::get('config')->trans($this->help),
        'tag' => $this->tag,
        'close' => !in_array($this->tag, $this->selfClose, true),
        'html' => $this->html,
        'attr' => $this->attr,
      ));
    return $result[0];
  }

  /**
   * Returns a configuration value as if it was a property of the class.
   *
   * @param string $name
   * @return mixed
   */
  public function __get($name) {
    return isset($this->config[$name]) ? $this->config[$name] : null;
  }

  /**
   * Sets a configuration value as if it was a property of the class.
   *
   * @param string $name
   * @param mixed $value
   */
  public function __set($name, $value) {
    $this->config[$name] = $value;
  }

  /**
   * Configures the component making sure that the user settings have the
   * highest priority.
   *
   * @param array $config [optional]
   * @param array $params [optional]
   */
  protected function configure($config = array(), $params = array()) {
    Service::mergeRecursive($config, $this->config);
    Service::mergeRecursive($config, $params);
    $this->config = $config;
  }

  /**
   * Updates the entity class with the value posted by the user.
   *
   * @param Em $em
   * @param $entity
   */
  public function prePersist(Em $em, $entity) {
    if ($value = Service::get("http.post.$this->name")) {
      $em->entitySet($entity, $this->name, $value);
    }
  }

} 